//
//  MusicPlayerViewController.m
//  FNer
//
//  Created by dllo on 15/11/6.
//  Copyright © 2015年 刘志强. All rights reserved.
//

#import "MusicPlayerViewController.h"
#import "MusicDetail.h"
#import "MusicErchDetailModel.h"
#import "MusicInfo.h"
#import <AVFoundation/AVFoundation.h>
#import "SessionTools.h"

@interface MusicPlayerViewController ()<LOAudioStreamerDelegate>
{
    float x;
    float y;
    float volume;
    id    delegate;
}



typedef enum : NSUInteger {
    MBAudioPlayTypeCircle,  //循环播放
    MBAudioPlayTypeRandom,  //随机播放
    MBAudioPlayTypeOneMusic,//单曲循环
    
} MBAudioPlayType;





@property (nonatomic, strong)CoreDataManager *coreDataManger;
@property (nonatomic, strong)NSString *strImage;
- (IBAction)voloumSlider:(UISlider *)sender;
@property (strong, nonatomic) IBOutlet UIImageView *backImageView;

@property (strong, nonatomic) IBOutlet UISlider *slider;
- (IBAction)SliderAction:(UISlider *)sender;

@property (strong, nonatomic) IBOutlet UIButton *TypeButton;





- (IBAction)TypeAction:(UIButton *)sender;



@property (assign, nonatomic) NSInteger playType;
@property (strong, nonatomic) IBOutlet UILabel *time;


@property (strong, nonatomic) IBOutlet UIProgressView *progress;
- (IBAction)DownLoadAction:(UIButton *)sender;



@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) IBOutlet UISlider *vSlider;

@end

@implementation MusicPlayerViewController

{
    CGPoint startPoint;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (_song_id == 0) {
        UIAlertView *alert =[[UIAlertView alloc]initWithTitle:@"当前还没有播放歌曲哦" message:nil delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        [alert show];

    }
    
}




+ (instancetype)sharePlayerDataHandel
{
    static MusicPlayerViewController *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[MusicPlayerViewController alloc]init];

       });
    return player;
}



- (void)viewDidLoad {
    [super viewDidLoad];


    // Do any additional setup after loading the view from its nib.
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"back" style:(UIBarButtonItemStyleDone) target:self action:@selector(backAction:)];
   self.playType = MBAudioPlayTypeCircle;;
   self.coreDataManger =[CoreDataManager shareManager];
   self.player = [LOAudioStreamer sharedStreamer];
   self.player.delegate = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(routeChange:) name:AVAudioSessionRouteChangeNotification object:nil];
    self.vSlider.transform = CGAffineTransformMakeRotation(M_PI *1.5);
    if (self.isLocal == NO) {
         [self getData];
    }
    else
    {
        MusicInfo *m = [self.allMusicArray objectAtIndex:self.indexRow];
        self.song_id = [m.musicLocalUrl integerValue];
        self.title = m.musicName;
        self.moveLabel.text = m.musicName;
    }


 
    
}



-(void)routeChange:(NSNotification *)notification{
    NSDictionary *dic=notification.userInfo;
    int changeReason= [dic[AVAudioSessionRouteChangeReasonKey] intValue];
    //等于AVAudioSessionRouteChangeReasonOldDeviceUnavailable表示旧输出不可用
    if (changeReason==AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
        AVAudioSessionRouteDescription *routeDescription=dic[AVAudioSessionRouteChangePreviousRouteKey];
        AVAudioSessionPortDescription *portDescription= [routeDescription.outputs firstObject];
        
        //原设备为耳机则暂停
        if ([portDescription.portType isEqualToString:@"Headphones"]) {
            [self pauseAction:self.pasueButton];
        }
    }
    
    
}




- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    NSLog(@"began %f==%f",touchPoint.x,touchPoint.y);
    x = (touchPoint.x);
    y = (touchPoint.y);
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    NSLog(@"end %f==%f",touchPoint.x,touchPoint.y);
    
    if ((touchPoint.y - y) >= 0)
    {
        NSLog(@"减小音量 1/10");
        NSLog(@"%f",self.slider.value);
        if ((self.vSlider.value) <= 0)
        {
            self.vSlider.value = 0;
            [self.vSlider sendActionsForControlEvents:(UIControlEventValueChanged)];
        }
        
        
        
        else
        {
            self.vSlider.value = self.vSlider.value - 0.02;
            [self.vSlider sendActionsForControlEvents:(UIControlEventValueChanged)];
            
        }
    }
    if ((y - touchPoint.y) >= 0)
    {
        NSLog(@"加大音量");
        if (self.vSlider.value >= 1)
        {
            self.vSlider.value = 1;
            [self.vSlider sendActionsForControlEvents:(UIControlEventValueChanged)];
        }
        else
        {
            self.vSlider.value = self.vSlider.value + 0.02;
            [self.vSlider sendActionsForControlEvents:(UIControlEventValueChanged)];
        }
        
    }
    
    y = touchPoint.y;
    
    
    //    if ((touchPoint.x - x) >= 50 && (touchPoint.y - y) <= 20 && (touchPoint.y - y) >= -20)
    //    {
    //        NSLog(@"快进");
    //
    //    }
    //    if ((touchPoint.x - x) >= 50 && (y - touchPoint.y) <= 50 && (y - touchPoint.y) >= -50)
    //    {
    //        NSLog(@"快进");
    //
    //    }
    //    if ((x - touchPoint.x) >= 50 && (touchPoint.y - y) <= 50 && (touchPoint.y - y) >= -50)
    //    {
    //        NSLog(@"快退");
    //
    //
    //    }
    //    if ((x - touchPoint.x) >= 50 && (y - touchPoint.y) <= 50 && (y - touchPoint.y) >= -50)
    //    {
    //        NSLog(@"快退");
    //    }
    NSLog(@"%f",touchPoint.y)
    
    
  

    
}




- (void)setSong_id:(NSInteger)song_id
{
    if (_song_id != song_id)
    {
        _song_id = song_id;
        if (self.isLocal == YES)
        {
            [self playLocalMusic];
        }
        else
        {
            [self getData];
        }

    }
}



- (void)setLockScreenNowPlayingInfo
{
    //更新锁屏时的歌曲信息4
    
    if (self.allMusicArray.count > 0) {
        MusicErchDetailModel *m = [self.allMusicArray objectAtIndex:_indexRow];
        
        
        
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        
        [dict setObject:m.name forKey:MPMediaItemPropertyTitle];
        [dict setObject:m.name forKey:MPMediaItemPropertyArtist];
        [dict setObject:m.name forKey:MPMediaItemPropertyAlbumTitle];
        [dict setObject:[NSNumber numberWithDouble:self.player.progress] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime]; //音乐当前已经播放时间
        
        
        
        [dict setObject:[NSNumber numberWithDouble: self.player.druation] forKey:MPMediaItemPropertyPlaybackDuration];//总过时间
        NSURL *url = [NSURL URLWithString:m.pic_500];
        
        UIImageView *imageV  =[[UIImageView alloc]init];
        [imageV sd_setImageWithURL:url placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            [dict setObject:[[MPMediaItemArtwork alloc] initWithImage:image]
                     forKey:MPMediaItemPropertyArtwork];
            [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:dict];
        }];
        

    }
    
}







//下一首
- (void)playNextMusic
{
    
    
   

    //NSLog(@"走了playNextMusic");
    switch (self.playType) {
            
        case MBAudioPlayTypeCircle:
        {
            //循环播放
            //NSLog(@"走了MBAudioPlayTypeCircle");
            _indexRow++;
            if (_indexRow == self.allMusicArray.count) {
                
                _indexRow = 0;
            }
            if (self.isLocal == NO) {
                MusicErchDetailModel *m = [self.allMusicArray objectAtIndex:self.indexRow];
//           = m.id;
                self.song_id = [m.id integerValue];
               
                self.title = m.name;
                self.moveLabel.text = m.name;
            }
            else
            {
                MusicInfo *m = [self.allMusicArray objectAtIndex:_indexRow];
         
                self.title = m.musicName;
                self.imageUrl = m.musicImage;
                self.moveLabel.text = m.musicName;
                self.song_id = [m.musicLocalUrl integerValue];
            
            }

     //       [self setLockScreenNowPlayingInfo];
            
            
        }
            break;
        case MBAudioPlayTypeRandom:
        {
            //随机播放
            //NSLog(@"走了MBAudioPlayTypeRandom:");
            [self randomWithTimes:5];
            
            if (self.indexRow == self.allMusicArray.count) {
                
                self.indexRow = 0;
            }
            if (self.isLocal == NO) {
                MusicErchDetailModel *m = [self.allMusicArray objectAtIndex:self.indexRow];
                self.song_id = [m.id integerValue];
                self.title = m.name;
                self.moveLabel.text = m.name;
                self.song_id = [m.id integerValue];

            }
            else
            {
                MusicInfo *m = [self.allMusicArray objectAtIndex:self.indexRow];
                self.song_id = [m.musicLocalUrl integerValue];
                self.title = m.musicName;
                self.imageUrl = m.musicImage;
                self.moveLabel.text = m.musicName;
            }
        }
            break;
        case MBAudioPlayTypeOneMusic:
        {
            //单曲循环
            [self playMusic];
            [self playLocalMusic];
        }
            break;
            
        default:
            break;
    }
    
}
//随机算法
-(void)randomWithTimes:(NSInteger)num
{
    NSInteger randomMusic = arc4random() % self.allMusicArray.count;
    
    //NSLog(@"随机值为：%ld",randomMusic);
    if (_indexRow == randomMusic && self.allMusicArray.count != 1) {
        //防止递归死循环
        if (num != 0) {
            num--;
            [self randomWithTimes:num];
            return;
        }else
        {
            randomMusic++;
            //递归多次还一样，就强行设一个了（低概率事件）
            _indexRow = randomMusic;
        }
    }
    else
    {
        //正常情况
        _indexRow = randomMusic;
    }
}




//获得数据
- (void)getData
{
    NSString *urlstr = [NSString stringWithFormat:@"http://echosystem.kibey.com/sound/info?sound_id=%ld", self.song_id];
    
    [AFNTools getAFN:urlstr andpara:nil andBlock:^(id result) {
        NSDictionary *dic = result;
        NSDictionary *resultDic = [dic objectForKey:@"result"];
        self.urlstr = [resultDic objectForKey:@"source"];
        self.name =  [resultDic objectForKey:@"name"];
        self.strImage =[resultDic objectForKey:@"pic_500"];
        NSURL *urlstr =[NSURL URLWithString:self.strImage];
        [self.backImageView sd_setImageWithURL:urlstr placeholderImage:nil];
        self.backImageView.userInteractionEnabled = YES;
        self.view.userInteractionEnabled = YES;

    
        [self playMusic];

        
       
    
    

        
        [self.player play];
        
        

    } andfailBlock:^(id fail) {
        
        NSLog(@"shibai");
    }];
}


- (void)playMusic
{
  
    if (![self.player isPlayingCurrentAudioWithURL:self.urlstr]) {
          [self.player stop];
        [self.player setAudioMetadataWithURL:self.urlstr];
        //   [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
        [self.player play];
    }
    

}


- (void)playLocalMusic
{
    
  
    
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
   NSString *file = [caches stringByAppendingPathComponent:[NSString stringWithFormat:@"lzq%ld.mp3" ,_song_id]];
    

    
    if (![self.player isPlayingCurrentAudioWithURL:file]) {

        [self.player stop];
        [self.player setLocalMetadataWithURL:file];
          [self.player play];
         self.player.volume =  self.vSlider.value;
    }
 
    NSURL *urlstr = [NSURL URLWithString:self.imageUrl];
    [self.backImageView sd_setImageWithURL:urlstr placeholderImage:nil];
}


//暂停 or 播放
- (IBAction)pauseAction:(UIButton *)sender
{
    if(self.player.isPlaying == NO){ //说明时暂停
        //   [sender setImage:[UIImage imageNamed:@"player_pause"] forState:UIControlStateNormal];
        [self.pasueButton setImage:[UIImage imageNamed:@"iconfont-zanting-2"] forState:UIControlStateNormal];
        [self.player play];
    }else if(self.player.isPlaying == YES){//正在播放
        [self.player pause];
        //      [sender setImage:[UIImage imageNamed:@"player_play"] forState:UIControlStateNormal];
        [self.pasueButton setImage:[UIImage imageNamed:@"iconfont-bofangqibofang"] forState:UIControlStateNormal];
    }
}
- (void)backAction:(UIBarButtonItem *)btn
{
    [self.navigationController popViewControllerAnimated:YES];
}



- (IBAction)SliderAction:(UISlider *)sender
{
    
    [self.player seekToTime: sender.value];
}


- (IBAction)TypeAction:(UIButton *)sender {
    if (self.playType == MBAudioPlayTypeCircle) {
        
        //NSLog(@"当前是循环播放模式");
        [sender setBackgroundImage:[UIImage imageNamed:@"iconfont-xunhuan"] forState:(UIControlStateNormal)];
        self.playType = MBAudioPlayTypeRandom;
    }
    else if (self.playType == MBAudioPlayTypeRandom) {
        
        self.playType = MBAudioPlayTypeOneMusic;
        //NSLog(@"当前是随机播放模式");
        [sender setBackgroundImage:[UIImage imageNamed:@"iconfont-suijibofang-1"] forState:(UIControlStateNormal)];
    }
    else  if (self.playType == MBAudioPlayTypeOneMusic) {
        self.playType = MBAudioPlayTypeCircle;
        [sender setBackgroundImage:[UIImage imageNamed:@"iconfont-danquxunhuan-2"] forState:(UIControlStateNormal)];
        //NSLog(@"当前是单曲循环模式");
    }
    

}

- (IBAction)lastAction:(UIButton *)sender
{
        self.indexRow--;
        if (self.indexRow < 0 ) {
            
            self.indexRow = self.allMusicArray.count - 1;
        }
        
    if (self.isLocal == NO) {
        MusicErchDetailModel *m = [self.allMusicArray objectAtIndex:self.indexRow];
        self.song_id = [m.id integerValue];
        self.title = m.name;
        self.moveLabel.text = m.name;
    }
    else
    {
        MusicInfo *m = [self.allMusicArray objectAtIndex:self.indexRow];
        self.song_id = [m.musicLocalUrl integerValue];
        self.title = m.musicName;
        self.moveLabel.text = m.musicName;
    }
    
    
        [self playMusic];
}



- (IBAction)nextAction:(UIButton *)sender
{
    [self playNextMusic];

}



-(void)audioStreamerDidFinishPlaying:(LOAudioStreamer *)streamer
{
    NSLog(@"asdasasddsdasda");
    
    [self playNextMusic];
}

- (void)audioStreamer:(LOAudioStreamer *)streamer didPlayingWithProgress:(float)progress
{


    

    self.slider.maximumValue = self.player.druation;//音乐总共时长
    


    self.slider.value = progress;//当前进度
    
    
    
    //
    //    //当前时长进度progress
    NSInteger proMin = (NSInteger)self.player.progress / 60;//当前分钟
    NSInteger proSec = (NSInteger)progress % 60;//当前秒
    //
    //    //duration 总时长
    NSInteger durMin = (NSInteger)self.player.druation / 60;//总秒
    NSInteger durSec = (NSInteger)self.player.druation % 60;//总分钟


    self.progress.progress = self.player.totalBuffer/self.player.druation;
    
     self.time.text = [NSString stringWithFormat:@"%02ld:%02ld/%02ld:%02ld", proMin, proSec, durMin, durSec];
    self.time.font = [UIFont systemFontOfSize:15];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}





- (IBAction)DownLoadAction:(UIButton *)sender
{
    NSLog(@"storeURL:%@",[self.coreDataManger applicationDocumentsDirectory]);

    

    if (self.isLocal == NO) {
        [SessionTools getLocalUrlWithNetUrl:self.urlstr andID:_song_id andBlock:^(id result) {
            
            NSEntityDescription *entity = [NSEntityDescription entityForName:@"MusicInfo" inManagedObjectContext:self.coreDataManger.managedObjectContext];
            //参数1.通过一个实体对象来初始化
            //参数2.交给谁去管理（数据管理器）
            MusicInfo *music = [[MusicInfo alloc]initWithEntity:entity insertIntoManagedObjectContext:self.coreDataManger.managedObjectContext];
            music.musicName = self.moveLabel.text;
            
            music.musicUrl = self.urlstr;
            music.musicLocalUrl = [NSNumber numberWithInteger:self.song_id];
            music.musicImage = self.strImage;
            [self.coreDataManger saveContext];
            
            NSLog(@"%@",result);
            
        }];

    }
    else
    {
        NSLog(@"yixiazai");
    }
    
 
}







   

- (IBAction)voloumSlider:(UISlider *)sender {
 


     [self.player setVolume:sender.value];
    
    
}
@end
